<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
//默认返回code
    protected $code = 200;
    //默认返回数据
    protected $data = [];
    //默认返回提示信息
    protected $msg = 'success';
    //http状态码
    protected $httpStatus = 200;

    /**
     * @desc 返回用户json数据
     * @return json
     */
    protected function json()
    {
        $response['code'] = $this->code;
        $msg_str = 'api.' . $this->code;
        $response['msg'] = trans('api.' . $this->code) == $msg_str ? $this->msg : trans('api.' . $this->code);
        $response['data'] = $this->_unsetNull($this->data);
        if ($this->code != 200){
            $this->httpStatus = 400;
        }
        return response()->json($response, $this->httpStatus);
    }


    /**
     * 去除返回NULL
     * @param $arr
     * @return array|string
     */
    function _unsetNull($arr)
    {
        if ($arr !== null) {
            if (is_array($arr)) {
                if (!empty($arr)) {
                    foreach ($arr as $key => $value) {
                        if ($value === null) {
                            $arr[$key] = '';
                        } else {
                            $arr[$key] = $this->_unsetNull($value);      //递归再去执行
                        }
                    }
                }
            } else {
                if ($arr === null) {
                    $arr = '';
                }         //注意三个等号
            }
        } else {
            $arr = '';
        }
        return $arr;
    }
}
